package com.sunwayworld.basemodule.business.outsource.io;

import com.sunwayworld.baseline.framework.override.LimsExcelHelper;
import com.sunwayworld.basemodule.business.outsource.bean.LimsOutsourceApplyBean;
import com.sunwayworld.basemodule.business.outsource.bean.LimsOutsourceSampleBean;
import com.sunwayworld.basemodule.business.outsource.service.LimsOutsourceApplyService;
import com.sunwayworld.basemodule.business.outsource.service.LimsOutsourceSampleService;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.exception.InvalidDataException;
import com.sunwayworld.framework.io.file.FilePathDTO;
import com.sunwayworld.framework.io.file.FilePathManager;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.NumberUtils;
import com.sunwayworld.framework.utils.ServletUtils;
import com.sunwayworld.framework.utils.StringUtils;
import com.sunwayworld.module.item.file.bean.CoreFileBean;
import com.sunwayworld.module.item.file.bean.CoreFileImportResultDTO;
import com.sunwayworld.module.item.file.function.CoreFileImportFunction;
import com.sunwayworld.module.item.file.manager.CoreFileManager;
import com.sunwayworld.module.item.file.utils.CoreFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @ClassName LimsOutsourceResultImportFileFunction
 * @Author zhoujq
 * @Date 2023/3/16
 * @Version 1.0
 **/
@Component(value = "LimsOutsourceResultImportFileFunction")
@GikamBean
public class LimsOutsourceResultImportFileFunction implements CoreFileImportFunction {

    @Autowired
    @Lazy
    private LimsOutsourceSampleService limsOutsourceSampleService;

    @Autowired
    @Lazy
    private LimsOutsourceApplyService limsOutsourceApplyService;

    @Override
    @Transactional
    public CoreFileImportResultDTO apply(CoreFileBean coreFileBean) {
        CoreFileImportResultDTO importResultRepresentation = new CoreFileImportResultDTO();
        FilePathDTO fr = CoreFileUtils.toFilePath(coreFileBean);

        // 从tos服务器下载
        CoreFileManager coreFileManager = ApplicationContextHelper.getBean(CoreFileManager.class);
        coreFileManager.download(coreFileBean, FilePathManager.getLocalPath(fr));

        String applyId = ServletUtils.getCurrentRequest().getParameter("applyId");
        List<LimsOutsourceSampleBean> importResults = LimsExcelHelper.readDataFromExcel(FilePathManager.getLocalPath(fr).toString(), 0, 1, LimsOutsourceSampleBean.class);
        if (!importResults.isEmpty() && !StringUtils.isBlank(applyId)) {
            List<LimsOutsourceSampleBean> oldBeans = limsOutsourceSampleService.selectListByFilter(SearchFilter.instance().match("applyId", applyId).filter(MatchPattern.EQ));
            importResults.stream().filter(Objects::nonNull).forEach(a -> {
                if (a.getId() == null) {
                    if (!StringUtils.isBlank(a.getExt$Item("validateimpmsg"))) {
                        a.setExt$Item("validateimpmsg", a.getExt$Item("validateimpmsg").concat("数据存在异常；"));
                    } else {
                        a.setExt$Item("validateimpmsg", "数据存在异常；");
                    }
                }
            });

            LimsOutsourceApplyBean applyBean = limsOutsourceApplyService.selectByIdIfPresent(NumberUtils.parseLong(applyId));
            if (applyBean == null || applyBean.getId() == null || !applyBean.getStatus().equals("logged")) {
                importResults.stream().filter(Objects::nonNull).forEach(a -> {
                    if (a.getId() == null) {
                        if (!StringUtils.isBlank(a.getExt$Item("validateimpmsg"))) {
                            a.setExt$Item("validateimpmsg", a.getExt$Item("validateimpmsg").concat("所选外包单存在异常，或已不可填写结果；"));
                        } else {
                            a.setExt$Item("validateimpmsg", "所选外包单存在异常，或已不可填写结果；");
                        }
                    }
                });
            }

            importResults.stream().filter(r -> r != null && r.getId() != null).filter(r -> oldBeans.stream().noneMatch(or -> or.getId().equals(r.getId()))).forEach(a -> {
                if (!StringUtils.isBlank(a.getExt$Item("validateimpmsg"))) {
                    a.setExt$Item("validateimpmsg", a.getExt$Item("validateimpmsg").concat("数据不属于此外包单；"));
                } else {
                    a.setExt$Item("validateimpmsg", "数据不属于此外包单；");
                }
            });
            // 返还校验结果
            if (importResults.stream().anyMatch(i -> !StringUtils.isEmpty(i.getExt$Item("validateimpmsg")))) {
                FilePathDTO filePathDTO = LimsExcelHelper.writeImportFailureListAsExcel(FilePathManager.getLocalPath(fr).toString(), importResults, 0, 1, "导入错误信息.xlsx", false);
                importResultRepresentation.setUrl(FilePathManager.getUrl(filePathDTO));
                importResultRepresentation.setMessage("导入失败");
                return importResultRepresentation;
            }

            oldBeans.forEach(ob -> {
                importResults.stream().filter(r -> r.getId().equals(ob.getId())).findAny().ifPresent(r -> {
                    ob.setTestResult(r.getTestResult());
                    ob.setTotalCost(r.getTotalCost());
                });
            });
            limsOutsourceSampleService.getDao().fastUpdate(oldBeans, "testResult", "totalCost");
        } else {
            throw new InvalidDataException("数据存在异常！");
        }
        importResultRepresentation.setMessage("导入成功");
        return importResultRepresentation;
    }

    @Override
    public boolean test(CoreFileBean coreFile, String service) {
        return true;
    }
}
